'use strict';

const path = require('path');
const _ = require('lodash');
const log4js = require('log4js');

const ALL_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];

function ctxParser(event) {
  let result = '';
  let ctx;
  let params;

  if (event.request) {
    ctx = event.request;
  } else if (_.isArray(event.data)) {
    event.data.forEach((arg, i) => {
      if (arg && _.isObject(arg) && _.isString(arg.originalUrl)) {
        ctx = event.req = arg;
        event.data.splice(i, 1);
      }
    });
  }

  if (ctx) {
    params = _.pick(ctx, [
      'params',
      'query',
      'body',
      'headers'
    ]);
    params.body = params.body || ctx.request.body;
    if (ctx.user) {
      params.user = ctx.user.name;
    }

    result = '[' + ctx.method + ' ' + ctx.originalUrl + ' ' + JSON.stringify(params) + ']';
  }

  return result;
}

function configure(config) {
  configure.logDir = config.dir.log;
  configure.appName = config.app.name;

  const appenders = [
    {
      type: 'console',
      layout: {
        type: 'pattern',
        pattern: '%[[%d] [%p] [%c] %x{ctx}%] %m',
        tokens: {
          ctx: ctxParser
        }
      }
    }
  ];

  ALL_LEVELS.slice(ALL_LEVELS.indexOf(config.log.level.toLowerCase()))
    .forEach((level) => {
      appenders.push({
        type: 'logLevelFilter',
        level: level.toUpperCase(),
        maxLevel: level.toUpperCase(),
        appender: {
          type: 'dateFile',
          filename: path.join(configure.logDir, `${configure.appName}-${level}`),
          pattern: '-yyyy-MM-dd.log',
          alwaysIncludePattern: true,
          layout: {
            type: 'pattern',
            pattern: '[%d] [%p] [%c] %x{ctx} %m',
            tokens: {
              ctx: ctxParser
            }
          }
        }
      });
    });

  log4js.configure({
    levels: {
      '[all]': config.log4js.level
    },
    appenders
  });
}

module.exports = configure;
